//
//  TFHorizontalTextFieldView.swift
//  TalkfunSDKDemo
//
//  Created by 莫瑞权 on 2022/4/25.
//  Copyright © 2022 Talkfun. All rights reserved.
//

import UIKit

class TFHorizontalTextFieldView: UIView, UITextViewDelegate {

    @objc public var status:TFChatAreaStatus = .AllNone
    var maxHeight:CGFloat = 80.0
    /**聊天*/
    @objc public let chatBtn = TalkfunIncreaseButton()
    /**弹幕*/
    @objc public let danmuBtn = TalkfunIncreaseButton()
    /**横屏输入框*/
    @objc public let textView = TF_TextView()
    /**表情*/
    @objc public let biaoqingBtn = UIButton()
    /**互动区域按钮*/
    @objc public let askAndChat_Btn = UIButton()
    /**窗口按钮*/
    @objc public let chuangkou_Btn = UIButton()
    @objc public var placeholder:NSString = ""
    //聊天框的背景图
    @objc public let fieldView = UIView()
    //聊天图片
    @objc public let inputImg = UIImageView()
    //记住TF_TextFieldView的高度
    @objc public var superHeight:CGFloat = 0
    //禁言提示
    @objc public let disabelChat = UILabel()
    @objc public var isChat:Bool = false
    @objc public var sendBlock: TFTextFieldViewSendBlock?
    @objc public var clickBlock: TFTextFieldViewClickBlock?
    //正在更新
    @objc public var isupadteTetxview:Bool = false
    //true为禁言false为解除禁言
    @objc public var isAbleChat:Bool = false
    //记住输入框的高度
    var fieldRect:CGRect = CGRect(x: 0, y: 0, width: 0, height: 0)
    var lastText:NSString = ""
    var keyBoardHight:CGFloat = 0
    let backgroundColorView = UIView()
    let gl = CAGradientLayer()
    var isIphoneF:CGFloat = 0
    var keyboardFrameEnd:CGRect = CGRect(x: 0, y: 0, width: 0, height: 0)
    var isOrientationiPhoneX:CGFloat = 0
    //显示键盘
    @objc func keyboardWillShow(noti:NSNotification) {
        if (self.currentTextView(self.textView) == true) {
           
            let keyboardInfo:NSDictionary = noti.userInfo! as NSDictionary
            
                let keyboardFrameEnd:NSValue = keyboardInfo.value(forKey: UIResponder.keyboardFrameEndUserInfoKey) as! NSValue
            
            let frame:CGRect = keyboardFrameEnd.cgRectValue
            self.keyboardFrameEnd = frame
                
            let animationDuration:NSNumber = keyboardInfo.value(forKey: UIResponder.keyboardAnimationDurationUserInfoKey) as! NSNumber
                //  执行动画
            let duration = animationDuration.floatValue
                //默认是56
                var aa:CGFloat = 56
                if self.frame.height>aa {
                    aa = self.frame.height
                }
           // 修改底部约束
                let  chatBarY:CGFloat = TalkfunSharedTools.getMainScreen().size.height - frame.size.height - aa
                
                
                UIView.animate(withDuration: TimeInterval(duration)) {
                    
                    self.fieldView.backgroundColor = UIColor(red: 244/255.0, green: 246/255.0, blue: 249/255.0, alpha: 1)
                    
                    self.frame = CGRect(x: 0, y: chatBarY, width:  TalkfunSharedTools.getMainScreen().size.width, height: aa)
                }

            }
        
       
        
    }
    //隐藏键盘
    @objc func KeyboardWillHide(noti:NSNotification) {
        if (self.currentTextView(self.textView) == true) {
              
                let keyboardInfo:NSDictionary = noti.userInfo! as NSDictionary
                
                let animationDuration:NSNumber = keyboardInfo.value(forKey: UIResponder.keyboardAnimationDurationUserInfoKey) as! NSNumber
                //  执行动画
                let duration = animationDuration.floatValue
                
                let  chatBarY:CGFloat = TalkfunSharedTools.getMainScreen().size.height - self.frame.height-self.isOrientationiPhoneX
                
                self.keyboardFrameEnd = CGRect(x: 0, y: 0, width: 0, height: 0)
                UIView.animate(withDuration: TimeInterval(duration)) {
                    
                    self.fieldView.backgroundColor = UIColor.white
                    
                    self.frame = CGRect(x: 0, y: chatBarY, width:  self.frame.size.width, height: self.frame.height)
                }

          
        }
      
    }
    @objc public func destroySharedIntance()
    {
        NotificationCenter.default.removeObserver(self)
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.isOrientationiPhoneX = 0
        if (self.isNotchScreen) {
          
            self.isOrientationiPhoneX = 21
            
        }
        //键盘显示前
        NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(noti:)), name: UIResponder.keyboardWillShowNotification, object: nil)

        //键盘隐藏前
        NotificationCenter.default.addObserver(self, selector: #selector(self.KeyboardWillHide(noti:)), name: UIResponder.keyboardWillHideNotification, object: nil)
        
        
        self.backgroundColorView.backgroundColor = UIColor.clear
        self.backgroundColorView.isUserInteractionEnabled = false
        self.addSubview(self.backgroundColorView)

        self.chatBtn.setImage(UIImage.init(named: "HTLive.bundle/liaotianqu"), for: .normal)
        self.chatBtn.setImage(UIImage.init(named: "HTLive.bundle/liaotianquClose"), for: .selected)
       
        self.chatBtn.tag = 2002
        self.addSubview(self.chatBtn)
        
        self.danmuBtn.setImage(UIImage.init(named: "HTLive.bundle/BarrageOn"), for: .normal)
        self.danmuBtn.setImage(UIImage.init(named: "HTLive.bundle/BarrageClose"), for: .selected)
  
        self.danmuBtn.tag = 2003
        self.addSubview(self.danmuBtn)

        self.chuangkou_Btn.setImage(UIImage.init(named: "HTLive.bundle/xianshichuangkou"), for: .normal)
        self.chuangkou_Btn.setImage(UIImage.init(named: "HTLive.bundle/hidenchuangkou"), for: .selected)

        self.chuangkou_Btn.tag = 2006
        self.chuangkou_Btn.isHidden = true
        self.addSubview(self.chuangkou_Btn)

        self.biaoqingBtn.setImage(UIImage.init(named: "HTLive.bundle/toolbar_imoji"), for: .normal)
        self.biaoqingBtn.setImage(UIImage.init(named: "HTLive.bundle/imoji"), for: .selected)
    
        self.biaoqingBtn.tag = 2004
        self.addSubview(self.biaoqingBtn)
        
        self.askAndChat_Btn.setImage(UIImage.init(named: "HTLive.bundle/toolbar_ask_green"), for: .normal)
        self.askAndChat_Btn.setImage(UIImage.init(named: "HTLive.bundle/toolbar_chat_green"), for: .selected)
        self.askAndChat_Btn.tag = 2005
        self.addSubview(self.askAndChat_Btn)

        self.fieldView.backgroundColor = UIColor.white
        self.fieldView.layer.cornerRadius = 20
        self.fieldView.layer.masksToBounds = true
        self.addSubview(self.fieldView)
        
        self.inputImg.image = UIImage.init(named: "HTLive.bundle/Input box_chat")
        self.fieldView.addSubview(self.inputImg)

        self.textView.delegate            = self
        self.textView.backgroundColor     = UIColor.clear
        self.textView.font                = UIFont.PingFang(size: 16)
        self.textView.layer.cornerRadius  = 20
        self.textView.layer.masksToBounds = true
        self.textView.returnKeyType       = .send
        self.textView.layoutManager.allowsNonContiguousLayout = false
        self.fieldView.addSubview(self.textView)

        self.disabelChat.textAlignment = .center
        self.disabelChat.textColor = UIColor(red: 150/255.0, green: 160/255.0, blue: 170/255.0, alpha: 1)
        self.disabelChat.font = UIFont.PingFang(size: 16)
        self.disabelChat.isHidden = true
        self.disabelChat.backgroundColor = self.fieldView.backgroundColor
        self.fieldView.addSubview(self.disabelChat)
        
        
        self.backgroundColorView.layer.addSublayer(self.gl)
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()

        self.gl.startPoint = CGPoint(x: 0.5, y: 1)
        self.gl.endPoint = CGPoint(x: 0.5, y: 0)
        self.gl.colors = [UIColor(red: 0, green: 0, blue: 0, alpha: 0.40).cgColor, UIColor(red: 30/255.0, green: 30/255.0, blue: 30/255.0, alpha: 0).cgColor ,UIColor(red: 96/255.0, green: 96/255.0, blue: 96/255.0, alpha: 0).cgColor]
        self.gl.locations = [0,1,1]
        
        
  
        self.gl.frame = self.backgroundColorView.bounds
        

        self.textView.tf_placeholder = self.placeholder as String
    }
    //修改输入框  禁言 isable
    @objc public func takeChatandAsk()
    {
        self.disabelChat.isHidden = true
        if (self.status == .Chat) { // 聊天
            self.chatBtn.isHidden = false
            self.danmuBtn.isHidden = false
            self.fieldView.isHidden = false
            self.biaoqingBtn.isHidden = false
            self.askAndChat_Btn.isHidden = false
            self.askAndChat_Btn.isUserInteractionEnabled = false
            self.askAndChat_Btn.isSelected = false
            //禁言中
            if (self.isAbleChat) {
                self.askAndChat_Btn.isHidden = true
                self.biaoqingBtn.isHidden = true
                self.placeholder = "说说你的问题..."
                self.inputImg.image = UIImage.init(named: "HTLive.bundle/Input box_ask")
                
                self.disabelChat.isHidden = false
//                self.disabelChat.backgroundColor = UIColor.red
            } else {
                self.askAndChat_Btn.isHidden = false
                if (self.askAndChat_Btn.isSelected) {

                    self.placeholder = "说说你的问题..."
                    self.inputImg.image = UIImage.init(named: "HTLive.bundle/Input box_ask")
                   
                    self.biaoqingBtn.isHidden = true
                } else {
                    self.placeholder = "说点什么吧..."
                    self.inputImg.image = UIImage.init(named: "HTLive.bundle/Input box_chat")
                    self.biaoqingBtn.isHidden = false
                    
                    self.askAndChat_Btn.isHidden = true
                }
            }
        } else if (self.status == .Ask) { //提问
            self.chatBtn.isHidden = false
            self.danmuBtn.isHidden = false
            self.fieldView.isHidden = false
            self.askAndChat_Btn.isHidden = false
            self.askAndChat_Btn.isSelected = true
            self.askAndChat_Btn.isUserInteractionEnabled = false
            self.placeholder = "说说你的问题..."
            self.inputImg.image = UIImage.init(named: "HTLive.bundle/Input box_ask")
            self.biaoqingBtn.isHidden = true
            
            self.askAndChat_Btn.isHidden = true
        } else if (self.status == .AllNone) { //两者都没有
            self.chatBtn.isHidden = false
            self.danmuBtn.isHidden = false
            self.fieldView.isHidden = true
            self.biaoqingBtn.isHidden = true
            self.askAndChat_Btn.isHidden = true
        } else if (self.status == .AskAndChat) { //全部都有
            self.chatBtn.isHidden = false
            self.danmuBtn.isHidden = false
            self.fieldView.isHidden = false
            self.biaoqingBtn.isHidden = false
            self.askAndChat_Btn.isHidden = false
            self.askAndChat_Btn.isUserInteractionEnabled = true
            if (self.isAbleChat) {
                self.askAndChat_Btn.isHidden = true
                self.biaoqingBtn.isHidden = true
                self.placeholder = "说说你的问题..."
                self.inputImg.image = UIImage.init(named: "HTLive.bundle/Input box_ask")
            } else {
                self.askAndChat_Btn.isHidden = false
                if (self.askAndChat_Btn.isSelected) {

                    self.placeholder = "说说你的问题..."
                    self.inputImg.image = UIImage.init(named: "HTLive.bundle/Input box_ask")
                    self.biaoqingBtn.isHidden = true
                } else {
                    self.placeholder = "说点什么吧..."
                    self.inputImg.image = UIImage.init(named: "HTLive.bundle/Input box_chat")
                    self.biaoqingBtn.isHidden = false
                  
                }
            }
            
        }
        //横屏设置

        if (self.chuangkou_Btn.isHidden) {
            self.chuangkou_Btn.frame = CGRect(x: self.frame.size.width, y: 16, width: 24, height: 24)
        } else {
            self.chuangkou_Btn.frame = CGRect(x: self.frame.size.width-40-24, y: 16, width: 24, height: 24)
        }
        
        self.askAndChat_Btn.frame = CGRect(x: self.chuangkou_Btn.frame.origin.x-32-40, y:(self.frame.height-40)/2, width: 40, height: 40)
        
        if (self.biaoqingBtn.isHidden) {
            
            
            if self.askAndChat_Btn.isHidden {
                self.biaoqingBtn.frame =  CGRect(x: self.frame.size.width, y: 16, width: 24, height: 24)
            }else
            {
                self.biaoqingBtn.frame = self.askAndChat_Btn.frame
            }
        } else {
            
            if self.askAndChat_Btn.isHidden {
                self.biaoqingBtn.frame = CGRect(x: self.askAndChat_Btn.frame.origin.x, y: 8, width: 40, height: 40)
            }else
            {
                self.biaoqingBtn.frame = CGRect(x: self.askAndChat_Btn.frame.origin.x-32-40, y: 8, width: 40, height: 40)
            }
            
        }
        
        self.chatBtn.frame = CGRect(x: 40, y: 16, width: 24, height: 24)
        self.danmuBtn.frame = CGRect(x: self.chatBtn.frame.maxX+32, y: 16, width: 24, height: 24)
    ////true为禁言false为解除禁言
        if (self.isAbleChat) {
            self.fieldView.frame = CGRect(x: self.danmuBtn.frame.maxX+32, y: 8, width: self.chuangkou_Btn.frame.origin.x-32-32-self.danmuBtn.frame.maxX, height: 40)
        } else {
           
            if (self.isupadteTetxview == false) {
                self.fieldView.frame = CGRect(x: self.danmuBtn.frame.maxX+32, y: 8, width: self.biaoqingBtn.frame.origin.x-32-32-self.danmuBtn.frame.maxX, height: 40)
            } else {
                self.fieldView.frame = CGRect(x: self.fieldRect.origin.x, y: self.fieldRect.origin.y, width: self.biaoqingBtn.frame.origin.x-self.fieldRect.origin.x-32, height: self.fieldRect.size.height)
            }
        }
        
        self.inputImg.frame = CGRect(x: 12, y: 10, width: 20, height: 20)
  
        let textViewX:CGFloat = 36
        let textViewW:CGFloat = self.fieldView.frame.size.width-textViewX-5
        let textViewH:CGFloat = self.fieldView.frame.size.height - 4
        let textViewY:CGFloat = (self.fieldView.frame.size.height-textViewH)*0.5
        
        self.textView.frame = CGRect(x: textViewX, y: textViewY, width: textViewW, height: textViewH)
        self.disabelChat.frame = self.fieldView.bounds
        
    }
    @objc public func buttonsAddTarget(target:NSObject,action:Selector)
   
    {
        self.chatBtn.addTarget(target, action: action, for: .touchUpInside)
        self.biaoqingBtn.addTarget(target, action: action, for: .touchUpInside)
        self.askAndChat_Btn.addTarget(target, action: action, for: .touchUpInside)
        self.chuangkou_Btn.addTarget(target, action: action, for: .touchUpInside)
        self.danmuBtn.addTarget(target, action: action, for: .touchUpInside)
    }

    func textViewDidChange(_ textView: UITextView) {


        let frame = textView.frame
       
        let constraintSize =  CGSize(width: frame.size.width, height: CGFloat(MAXFLOAT))
        
        var size = textView.sizeThatFits(constraintSize)
       
        
        if (size.height<=frame.size.height) {
           
        }else{
            if (size.height>=maxHeight){
                size.height = maxHeight
                textView.isScrollEnabled = true  // 允许滚动
            }else{
                textView.isScrollEnabled = false   // 不允许滚动
            }
        }
        
        textView.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: size.height)
        
        
        self.fieldView.frame = CGRect(x: self.danmuBtn.frame.maxX+32, y: 8, width: frame.size.width+41, height: size.height+4)
        self.fieldRect = self.fieldView.frame
        let superHeight:CGFloat = self.fieldView.frame.maxY+8
        
        if (self.isNotchScreen) {
                self.isIphoneF = 21;
            } else {
                self.isIphoneF = 0;
        }
       
        UIView.animate(withDuration: 0) {
            self.frame = CGRect(x: self.frame.origin.x, y: UIScreen.main.bounds.height-(self.keyboardFrameEnd.height+superHeight), width: self.frame.size.width, height: superHeight)
           
        }
        
        self.superHeight = superHeight;

        let size_H = TalkfunSharedTools.getSizeLabel(labelString: NSMutableAttributedString.init(string: textView.text), labelWidth: UIScreen.main.bounds.width-20, labelfont: UIFont.systemFont(ofSize: 17))
        
        
        if (textView.text.count>self.lastText.length+5) {
            if (size_H.height>maxHeight) {
                textView.setContentOffset(CGPoint(x: 0, y: (size_H.height-maxHeight)), animated: false)
               
            }
        }

        self.lastText = textView.text! as NSString
        
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
 
        if text == "\n" {
            
            let whiteSpace = NSCharacterSet.whitespacesAndNewlines
            
            let str =   NSString.init(string: textView.text).trimmingCharacters(in: whiteSpace)
            

            if (str.count != 0) {
       
                if self.sendBlock != nil {
        
                    self.sendBlock!(self.textView)

                    self.superHeight = 0;
                    self.fieldRect = .zero;
                   
                    self.textView.resignFirstResponder()
                    
                 
                    self.textView.tf_placeholder = self.placeholder as String
                    }
                
                
            }
            return false
        }
        return true
    }
    
    func textViewDidBeginEditing(_ textView: UITextView) {

        self.lastText = ""
        
        self.textView.tf_placeholder = self.placeholder as String
        if (self.isChat) {
            if (self.fieldRect.size.height > 0) {
                self.isupadteTetxview = true;
            }
        } else {
            if (self.fieldRect.size.height > 0) {
                self.isupadteTetxview = false;
            }
        }
       
        if self.clickBlock != nil {
            self.clickBlock!(true)
        }
    }
    
    //textViewDidEndEditing
    func textViewDidEndEditing(_ textView: UITextView) {
        if (textView.text.count > 0) {
            self.isupadteTetxview = true
        } else {
            self.isupadteTetxview = false
            
        }
    }
    
    @objc public func udateFrame(height: CGFloat,textView:UITextView)
    
    {
        
            let frame = textView.frame
           
            let constraintSize = CGSize(width: frame.size.width, height: CGFloat(MAXFLOAT))
            
            var size = textView.sizeThatFits(constraintSize)
           
            
            if (size.height<=frame.size.height) {

            }else{
                if (size.height>=maxHeight){
                    size.height = maxHeight;
                    textView.isScrollEnabled = true;   // 允许滚动
                }else{
                    textView.isScrollEnabled = false;    // 不允许滚动
                }
            }
        
        textView.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: size.height)
        
        self.fieldView.frame = CGRect(x: self.danmuBtn.frame.maxX+32, y: 0, width: frame.size.width+41, height: size.height+4)
        self.fieldRect = self.fieldView.frame
        let superHeight:CGFloat = self.fieldView.frame.maxY+8
        
        
        UIView.animate(withDuration: 0) {
         
            self.frame = CGRect(x: self.frame.origin.x, y: UIScreen.main.bounds.height-(height+superHeight), width: self.frame.size.width, height: superHeight)
        }
        
        self.superHeight = superHeight

        let size_H = TalkfunSharedTools.getSizeLabel(labelString: NSMutableAttributedString.init(string: textView.text), labelWidth: UIScreen.main.bounds.width-20, labelfont: UIFont.systemFont(ofSize: 17))

        if (textView.text.count>self.lastText.length+5) {
            if (size_H.height>maxHeight) {
                textView.setContentOffset(CGPoint(x: 0, y: (size_H.height-maxHeight)), animated: false)
               
            }
        }

        self.lastText = textView.text! as NSString
        
    }
    
}
